#include <iostream>
#include "Sock.hpp"
#include "Protocol.hpp"

using namespace dsh_protocol;

static void Usage(const std::string &process)
{
    std::cout << "\nUsage: " << process << " ip port\n"
              << std::endl;
}

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(1);
    }
    std::string server_ip = argv[1];
    uint16_t server_port = atoi(argv[2]);
    Sock sock;
    int sockfd = sock.Socket();                        // 创建套接字
    if (!sock.Connect(sockfd, server_ip, server_port)) // 连接
    {
        std::cerr << "Connect error" << std::endl;
        exit(2);
    }

    // 通信
    bool quit = false;
    std::string s = "";
    while (true)
    {
        // 1.获取
        std::cout << "请输入(格式: x op y): ";
        Request req;
        std::cin >> req.x_ >> req.op_ >> req.y_;
        if (s == "quit")
        {
            close(sockfd);
            break;
        }

        // 2.序列化
        s = req.Serialize();
        // 3.添加报头
        s = Encode(s);
        // 4.发送给服务端
        Send(sockfd, s);

        // 5.读取
        std::string buffer;
        Response resp;
        while (true)
        {
            bool ret = Recv(sockfd, &buffer);
            if (!ret)
            {
                quit = true;
                break;
            }
            // 6.去掉报头
            std::string package = Decode(buffer);
            if (package.empty())
                continue;
            resp.Deserialize(package);
            std::string err;
            switch (resp.code_)
            {
            case 1:
                err = "除0错误";
                break;
            case 2:
                err = "模0错误";
                break;
            case 3:
                err = "非法操作";
                break;
            default:
                std::cout << req.x_ << req.op_ << req.y_ << " = " << resp.result_ << " [success]" << std::endl;
                break;
            }
            if (!err.empty())
                std::cerr << err << std::endl;
            break;
        }
    }
    close(sockfd);
    return 0;
}